(* 
Copyright (c) 2008, Raymond W. Vernagus (R.Vernagus@gmail.com)
All rights reserved.

Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:

  * Redistributions of source code must retain the above copyright notice,
    this list of conditions and the following disclaimer.
  * Redistributions in binary form must reproduce the above copyright notice,
    this list of conditions and the following disclaimer in the documentation
    and/or other materials provided with the distribution.
  * Neither the name of Raymond W. Vernagus nor the names of FsUnit's
    contributors may be used to endorse or promote products derived from this
    software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*)
#light
open Microsoft.FSharp.Text.Printf

type Expectation =
    | True
    | False
    | Empty
    | NullOrEmpty
    | Null
    | SameAs of obj

type Result =
    | Pass
    | Fail
    | Error

type SpecResult(result, expected, actual, label) =
    member s.Label = label
    member s.Result = result
    member s.Expected = expected
    member s.Actual = actual
    abstract Message : string
    default s.Message =
        let nl = System.Environment.NewLine
        match result with
        | Pass  -> sprintf "%s%s  Expected: %s%s  Actual: %s" label nl expected nl actual
        | Fail  -> sprintf "%s%s  Expected: %s%s  But was: %s" label nl expected nl actual
        | Error -> "Error!"
    new(result) = SpecResult(result, "?", "?")
    new(result, expected, actual) = SpecResult(result, expected, actual, "?")
        
[<AbstractClass>]
type Spec() =
    abstract Check : unit -> SpecResult

type LabeledSpec(label: string, spec: Spec) =
    inherit Spec()
    override s.Check() =
        let result = spec.Check()
        SpecResult(result.Result, result.Expected, result.Actual, label)
        
type ResultStore() =
    let mutable results = []
    
    let passed (r: SpecResult) =
        match r.Result with
        | Pass -> true
        | _    -> false
        
    let failed (r: SpecResult) =
        match r.Result with
        | Fail -> true
        | _    -> false
        
    let passingResults() = results |> List.filter passed
    
    let failingResults() = results |> List.filter failed

    member x.Add (r: SpecResult) = results <- r::results
    
    member x.Summarize() =
        let nl = System.Environment.NewLine
        let buff = System.Text.StringBuilder()
        bprintf buff "%d passed.%s" (passingResults() |> List.length) nl
        bprintf buff "%d failed!%s" (failingResults() |> List.length) nl
        failingResults()
            |> List.iter (fun x -> bprintf buff "  FAILED %s%s%s" x.Label nl x.Message)
        buff.ToString()
        
let check (spec: #Spec) = spec.Check().Result

let should f x = f x

let (|!|) (lbl: string) (spec: Spec) = LabeledSpec(lbl, spec)

let equal x y =
    let result = y = x
    { new Spec() with
        member s.Check() =
            let sact = any_to_string y
            let sexp = any_to_string x
            if result then SpecResult(Pass, sexp, sact)
            else SpecResult(Fail, sexp, sact) }

let have n label seq =
    let length = Seq.length seq
    { new Spec() with
        member s.Check() =
            if length = n then
                { new SpecResult(Pass) with
                    member r.Message = sprintf "<%A> has %d %s." seq n label }
            else 
                { new SpecResult(Fail) with
                    member r.Message = sprintf "<%A> should have %d %s." seq n label } }

let contain item seq =
    let result = seq |> Seq.tryfind ((=) item)
    { new Spec() with
        member s.Check() =
            match result with
            | Some _ ->
                { new SpecResult(Pass) with
                    member r.Message = sprintf "<%A> contains %A." seq item }
            | None ->
                { new SpecResult(Fail) with
                    member r.Message = sprintf "<%A> should contain %A." seq item } }

let be exp actual =
    let actual = box actual
    let equals x =
        if actual.Equals(x) then Pass
        else Fail
    { new Spec() with
        member s.Check() =
            let sexp = any_to_string exp
            let sact = any_to_string actual
            match exp with
            | True         -> SpecResult(equals true, sexp, sact)
            | False        -> SpecResult(equals false, sexp, sact)
            | Empty        -> SpecResult(equals string.Empty, sexp, sact)
            | NullOrEmpty  -> 
                if string.IsNullOrEmpty(actual :?> string) then SpecResult(Pass, sexp, sact)
                else SpecResult(Fail, sexp, sact)
            | Null         ->
                if actual = null then SpecResult(Pass, sexp, sact)
                else SpecResult(Fail, sexp, sact)
            | SameAs other ->
                if obj.ReferenceEquals(actual,other) then SpecResult(Pass, sexp, sact)
                else SpecResult(Fail, sexp, sact) }

let raise' exType f =
    { new Spec() with
        member s.Check() =
            let sexp = any_to_string exType
            try
                f()
                SpecResult(Fail, sexp, "no exception was raised")
            with
            | ex ->
                let actualType = ex.GetType()
                if exType = actualType then SpecResult(Pass, sexp, actualType.ToString())
                else SpecResult(Fail, sexp, actualType.ToString()) }

let not' (f: 'a -> Spec) x =
    let spec = f x
    let result = spec.Check()
    { new Spec() with
        member s.Check() =
            let sexp = sprintf "not %s" result.Expected
            let sact = result.Actual
            match result.Result with
            | Pass  -> SpecResult(Fail, sexp, sact)
            | Fail  -> SpecResult(Pass, sexp, sact)
            | Error -> SpecResult(Error) }

let results = ResultStore()

let spec desc spec =
    let s = desc |!| spec
    let result = s.Check()
    results.Add result
